package com.smart.sso.server.controller.admin;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smart.mvc.controller.BaseController;
import com.smart.mvc.model.Result;
import com.smart.mvc.model.ResultCode;
import com.smart.mvc.validator.Validator;
import com.smart.mvc.validator.annotation.ValidateParam;
import com.smart.sso.server.common.LoginUser;
import com.smart.sso.server.common.TokenManager;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "应用管理")
@Controller
@RequestMapping("/admin/token")
public class TokenController extends BaseController {

    @Resource
    private TokenManager tokenManager;

    @ApiOperation("初始页")
    @RequestMapping(method = RequestMethod.GET)
    public String execute(Model model) {
        model.addAttribute("tokenList", tokenManager.tokenList());
        return "/admin/token";
    }

    @ApiOperation("验证门卡编码")
    @RequestMapping(value = "/validateCode", method = RequestMethod.POST)
    public @ResponseBody Result validateCode(
            @ApiParam(value = "id") Integer id,
            @ApiParam(value = "门卡编码", required = true) @ValidateParam({
                Validator.NOT_BLANK }) String token) {
        Result result = Result.createSuccessResult();
        LoginUser user = tokenManager.validate(token);
        if (null == user || user.getUserId() != id) {
            result.setCode(ResultCode.ERROR).setMessage("门卡编码已失效");
        }
        return result;
    }

    @ApiOperation("禁用")
    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    public @ResponseBody Result enable(
            @ApiParam(value = "id", required = true) @ValidateParam({
                Validator.NOT_BLANK }) String token) {
        tokenManager.remove(token);
        return Result.createSuccessResult();
    }

}
